package ylh.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
import ylh.common.R;
import ylh.dto.SetmealDto;
import ylh.entity.Category;
import ylh.entity.Dish;
import ylh.entity.Setmeal;
import ylh.entity.SetmealDish;
import ylh.service.CategoryService;
import ylh.service.DishService;
import ylh.service.SetmealDishService;
import ylh.service.SetmealService;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SetmealDishService setmealDishService;

    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize, String name) {
        log.info("page = {},pageSize = {}", page, pageSize);
        //构造分页构造器
        Page<Setmeal> pageInfo = new Page<>(page, pageSize);
        Page<SetmealDto> dtoPage = new Page<>();

        //构造条件构造器
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null, Setmeal::getName, name);
        //按更新时间排序
        queryWrapper.orderByAsc(Setmeal::getUpdateTime);

        //执行查询
        setmealService.page(pageInfo, queryWrapper);
        BeanUtils.copyProperties(pageInfo, dtoPage, "records");

        List<Setmeal> setmeals = pageInfo.getRecords();
        List<SetmealDto> setmealDtos = setmeals.stream().map((item) -> {
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(item, setmealDto);
            Category category = categoryService.getById(item.getCategoryId());

            if (category.getName() != null) {
                setmealDto.setCategoryName(category.getName());
            }
            return setmealDto;
        }).collect(Collectors.toList());

        dtoPage.setRecords(setmealDtos);
        return R.success(dtoPage);
    }

    @PostMapping
    @CacheEvict(value = "setmealCache", allEntries = true)
    public R<String> save(@RequestBody SetmealDto setmealDto) {

        setmealService.saveWithDto(setmealDto);

        return R.success("成功添加");
    }


    @GetMapping("/{id}")
    public R<SetmealDto> getById(@PathVariable Long id) {
        SetmealDto setmealDto = setmealService.getWithDto(id);
        return R.success(setmealDto);
    }


    @PutMapping
    public R<String> updateById(@RequestBody SetmealDto setmealDto) {
        setmealService.updateWithDto(setmealDto);
        return R.success("修改成功");
    }


    @DeleteMapping
    @CacheEvict(value = "setmealCache", allEntries = true)
    public R<String> deleteByIds(@RequestParam List<Long> ids) {
        setmealService.deleteBy(ids);
        return R.success("成功删除");
    }

    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable int status, @RequestParam List<Long> ids) {
        Setmeal setmeal = new Setmeal();
        setmeal.setStatus(status);
        for (Long id :
                ids) {
            setmeal.setId(id);
            setmealService.updateById(setmeal);
        }

        return R.success("成功更改");
    }

    @GetMapping("/list")
    @Cacheable(value = "setmealCache",key = "#setmeal.categoryId + '_' + #setmeal.status")
    public R<List<SetmealDto>> getList(Setmeal setmeal) {

        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Setmeal::getCategoryId, setmeal.getCategoryId());
        queryWrapper.eq(Setmeal::getStatus, setmeal.getStatus());
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);

        List<Setmeal> list = setmealService.list(queryWrapper);

        List<SetmealDto> setmealDtos = list.stream().map((item) -> {
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(item, setmealDto);

            LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(SetmealDish::getSetmealId, item.getId());

            setmealDto.setSetmealDishes(setmealDishService.list(lambdaQueryWrapper));

            return setmealDto;
        }).collect(Collectors.toList());
        return R.success(setmealDtos);
    }

    @GetMapping("/dish/{id}")
    public R<List<Dish>> getDishById(@PathVariable Long id) {

        Setmeal setmeal = setmealService.getById(id);

        SetmealDto setmealDto = new SetmealDto();
        BeanUtils.copyProperties(setmeal, setmealDto);

        LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SetmealDish::getSetmealId, setmeal.getId());

        List<SetmealDish> setmealDishes = setmealDishService.list(lambdaQueryWrapper);

        List<Dish> dishes = setmealDishes.stream().map((item)->{
            Dish dish = dishService.getById(item.getDishId());
            return dish;
        }).collect(Collectors.toList());
        return R.success(dishes);
    }
}
